package com.koelo.kiss.re.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.Logger;


public class Session 
	implements ISession {
	
	private static final long serialVersionUID = -3645453055619449405L;
	private Logger LOGGER = Logger.getLogger(Session.class);
	private Map<String, Object> map;
	private Map<String, Object> variables;
	
	public Session() {
		
		this.map = new HashMap<String, Object>();
		this.variables = new HashMap<String, Object>();
	}
	
	@Override
	public void set(String key, Object value) {
		
		LOGGER.debug("Adding object to session " + "{" + key + " : " + value + "}");
		this.map.put(key, value);
	}
	
	@Override
	public Object get(String key) {

		Object value = this.map.get(key);
		LOGGER.debug("Getting object from session " + "{" + key + " : " + value + "}");
		return value;
	}

	@Override
	public Object get(String key, Object defaultValue) {
		
		Object value = get(key);
		if (value == null) {
			value = defaultValue;
			LOGGER.debug("Getting default object from session " + "{" + key + " : " + value + "}");
		}
		return value;
	}

	@Override
	public Object remove(String key) {

		Object value = this.map.remove(key);
		LOGGER.debug("Removing object from session " + "{" + key + " : " + value + "}");
		return value;
	}

	@Override
	public void setVariables(Map<String, Object> variables) {
		
		this.variables = variables;
	}
	
	@Override
	public Map<String, Object> getVariables() {
		
		return this.variables;
	}
	
	@Override
	public Object getVariable(String key) {

		Object value = this.variables.get(key);
		LOGGER.debug("Getting variable from session " + "{" + key + " : " + value + "}");
		return value;
	}
	
	@Override
	public String toString() {
		
		String buffer = "{\"session\": {";
		Iterator<String> keys = this.map.keySet().iterator();
		while (keys.hasNext()) {
			String key = keys.next();
			Object value = this.map.get(key);
			buffer += "\"" + key + "\": \"" + value + "\", ";
		}
		return buffer.substring(0, buffer.length() - 2) + "}}";
	}	
}
